<template>
  <q-page class="q-pa-md">
    <p>
      {{debugStr}}
    </p>
    <q-btn class="float-right" color="primary" icon="arrow_back" outline title="返回" to="/" />
    <div class="q-pb-md text-h5">{{ pageTitle }}</div>
    <div class="q-pa-md shadow-2">
      <img :src="props.logo" :style="props.logoStyle" v-if="props.showLogo" />
      <div class="q-mt-sm text-subtitle1 text-weight-bolder">{{ fx.packageInfo.productName }}</div>
      <slot></slot>
      <div class="q-mt-sm row no-wrap">
        <div class="q-mr-md about-label">应用版本</div>
        <div>{{ fx.packageInfo.productName }}&nbsp;{{ appVersion }}
          <q-btn v-if="isInAppMode && props.urlForUpgradeCheck" :loading="updateCheckingState"
            :disable="updateCheckingState" color="primary" class="q-px-sm" dense size="sm" @click="checkForUpdate">检查更新
          </q-btn>
        </div>
      </div>
      <div class="row no-wrap">
        <div class="q-mr-md about-label">后端版本</div>
        <div>{{ backendVersion }}</div>
      </div>
      <div class="q-mt-sm row no-wrap" v-if="props.authTo">
        <div class="q-mr-md about-label">使用授权</div>
        <div>{{ props.authTo }}</div>
      </div>
    </div>
    <q-dialog persistent transition-hide="none" transition-show="none" v-model="showingApkDownloadDlg">
      <q-card style="width: 90%">
        <q-card-section>
          <div class="text-center">更新包下载中...</div>
          <q-linear-progress
            class="q-mt-md"
            size="sm"
            :value="apkDownloadProcess"
            color="primary" />
        </q-card-section>
      </q-card>
    </q-dialog>
  </q-page>
</template>

<script lang="ts">
export default {
  name: 'pdaAboutStd'
}
</script>

<script lang="ts" setup>
import {useTitleHelper} from '@njt/foundation/hooks/titleHelper'
import { App } from '@capacitor/app'
import {computed, onMounted, ref} from 'vue'
import ApkUpdater from 'cordova-plugin-apkupdater'
import {useQuasar} from 'quasar'
//@ts-ignore
import njtLogo from '@njt/foundation/assets/njtlogo.png'

const pageTitle = '关于'
useTitleHelper(pageTitle)

const $q = useQuasar()

const props = defineProps({
  logoStyle: {
    type: Object,
    default: null,
  },
  logo: {
    default: njtLogo,
  },
  authTo: {
    type: String,
    default:''
  },
  urlForUpgradeCheck: {
    type: String,
    default: ''
  },
  showLogo: {
    default: true,
    type: Boolean
  }
})

let appVersion = ref('加载中...')
let updateCheckingState = ref(false)
let backendVersion = ref('加载中...')
let showingApkDownloadDlg = ref(false)
let debugStr = ref('')

const isInAppMode = computed(() => {
  return !!($q.capacitor)
})

interface UpgradeInfo {
  version: string
  appUrl: string
}

const checkForUpdate = function () {
  updateCheckingState.value = true
  $f.feAxios.get<UpgradeInfo>(`${props.urlForUpgradeCheck}?rand=${Date.now()}`)
    .then((resp) => {
      if (resp.data.version != appVersion.value) {
        void $f.ui.messageBox({
          caption: '确认',
          text: '发现新版本:' + resp.data.version + ', 确定更新吗?',
          icon: 'Question',
          buttons: 'OkCancel'
        }).then((btn) => {
          if (btn === 'ok') {
            showingApkDownloadDlg.value = true
            debugStr.value = resp.data.appUrl
            downloadApkAndUpgrade(resp.data.appUrl)
          }
        })
      } else {
        void $f.ui.messageBox({
          caption: '提示',
          text: '已经是最新版本',
          icon: 'Information',
          buttons: 'Close'
        })
      }
    })
    .catch((err) => {
      $f.ui.showNotifyFailed($f.getAxiosErrMsg(err))
    })
    .finally(() => {
      updateCheckingState.value = false
    })
}
let apkDownloadProcess = ref(0)
const downloadApkAndUpgrade = function (apkUrl: string) {
  void ApkUpdater.download(
    apkUrl,
    {
      onDownloadProgress: (download) => {
        apkDownloadProcess.value = download.progress
      }
    },
    () => {
      showingApkDownloadDlg.value = false
      debugStr.value = '准备安装'
      void ApkUpdater.install()
    },
    (err:any) => {
      showingApkDownloadDlg.value = false

      debugStr.value = `更新包下载出错${err.message ? (`:${err.message}`):''}`
      $f.ui.showNotifyFailed(`更新包下载出错${err.message ? (`:${err.message}`):''}`)
    }
  )
}

interface BuildInfo {
  ver: string
}

onMounted(() => {
  if (isInAppMode.value) {
    void App.getInfo().then((info) => {
      appVersion.value = info.version
    })
  } else {
    $f.feAxios
      .get<BuildInfo>( $f.getSiteUrl('build-info.json'))
      .then((resp) => {
        appVersion.value = resp.data.ver
      })
      .catch((err) => {
        $f.ui.showNotifyFailed($f.getAxiosErrMsg(err))
      })
  }
})
$f.axios.get<string>('/comm/about/get-about-info').then((resp) => {
  backendVersion.value = resp.data
}).catch((err) => {
  $f.ui.showNotifyFailed($f.getAxiosErrMsg(err))
})
const fx = $f
</script>

<style lang="sass" scoped>
.about-label
  width: 70px
</style>
